package com.zhihaoliang.jobschedulertrain

import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Messenger
import android.os.PersistableBundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.zhihaoliang.jobschedulertrain.databinding.ActivityMainBinding


private const val TAG = "MainActivity"

class MainActivity : AppCompatActivity() {

    private lateinit var mActivityMainBinding:ActivityMainBinding

    private lateinit var mHandler: InComingMsgHandler

    private lateinit var mServicecomponent: ComponentName

    private var mJobId = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mActivityMainBinding = ActivityMainBinding.inflate(layoutInflater).apply {
            setContentView(root)
        }

        mHandler= InComingMsgHandler(this)
        mServicecomponent = ComponentName(this,MyJobService::class.java)
    }

    override fun onStart() {
        super.onStart()
        val startIntent = Intent(this,MyJobService::class.java).apply {
            putExtra(MESSENGER_INTENT_KEY,Messenger(mHandler))
        }
        startService(startIntent)
    }

    override fun onStop() {
        stopService(Intent(this,MyJobService::class.java))
        super.onStop()
    }

    fun onClick(view: View){
        when(view){
            mActivityMainBinding.finshButton ->finshJob()
            mActivityMainBinding.cancleButton -> (getSystemService(Context.JOB_SCHEDULER_SERVICE)as JobScheduler).cancelAll()
            mActivityMainBinding.scheduleButton -> schduleJob()
        }
    }

    private fun schduleJob(){
        val builder = JobInfo.Builder(mJobId++,mServicecomponent)
        val delay =  mActivityMainBinding.delayTime.text.toString()
        if(delay.isNotEmpty()){
            //设置至少延迟多久后执行，单位毫秒
            builder.setMinimumLatency(delay.toLong()*1000)
        }

        val deadline = mActivityMainBinding.deadlineTime.text.toString()
        if(deadline.isNotEmpty()){
            //最后执行的期限
            builder.setOverrideDeadline(delay.toLong()*1000)
        }

        //设置需要的网络条件，有三个取值：
        //JobInfo.NETWORK_TYPE_NONE（无网络时执行，默认）、
        //JobInfo.NETWORK_TYPE_ANY（有网络时执行）、
        //JobInfo.NETWORK_TYPE_UNMETERED（网络无需付费时执行）
        if(mActivityMainBinding.checkboxUnmetered.isChecked){
            builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
        }else{
            builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
        }
        //是否在空闲时执行
        builder.setRequiresDeviceIdle(mActivityMainBinding.checkboxIdle.isChecked());

        //是否在充电时执行
        builder.setRequiresCharging(mActivityMainBinding.checkboxCharging.isChecked());

        //设置jobService的执行时间
        val extras = PersistableBundle()
        var workDuration: String = mActivityMainBinding.durationTime.getText().toString()
        if (TextUtils.isEmpty(workDuration)) {
            workDuration = "1"
        }
        extras.putLong(WORK_DURATION_KEY, java.lang.Long.valueOf(workDuration) * 1000)
        builder.setExtras(extras)
        (getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler).schedule(builder.build())
    }

    private fun finshJob(){
        val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
        val allPendingJops = jobScheduler.allPendingJobs
        if(allPendingJops.size > 0){
            val  id = allPendingJops.first().id
            jobScheduler.cancel(id)
            Log.e(TAG,getString(R.string.cancelled_job,id))
            return
        }
        Log.e(TAG,getString(R.string.no_jobs_to_cancel))
    }

    /**
     * 打开知识灯，更新开始任务状态
     */
    fun startJub(jobId: Any? = null, action: String = ""){
        mActivityMainBinding.onstarttask.setBackgroundColor(ContextCompat.getColor(this,R.color.start_received))
        updateParamsTextView(jobId,action)
    }

    /**
     * 打开知识灯，更新结束任务状态
     */
    fun stopJub(jobId: Any? = null, action: String = ""){
        mActivityMainBinding.onstoptask.setBackgroundColor(ContextCompat.getColor(this,R.color.start_received))
        updateParamsTextView(jobId,action)
    }

    fun clearState(state:Int){
        if(state == MSG_UNCOLOR_START){
            mActivityMainBinding.onstarttask.setBackgroundColor(ContextCompat.getColor(this, R.color.none_received))
        }else{
            mActivityMainBinding.onstoptask.setBackgroundColor(ContextCompat.getColor(this, R.color.none_received))

        }
        updateParamsTextView()
    }

    /**
     * 更新任务状态
     */
    private fun updateParamsTextView(jobId: Any? = null, action: String = "") {
        if (jobId == null) {
            mActivityMainBinding.taskParams.text = ""
            return
        }
        mActivityMainBinding.taskParams.text = getString(R.string.job_status, jobId.toString(), action)
    }
}
